<template>
  <q-page class="cc-admin">
    <div>
      <div class="row">
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-label>角色名称：</q-item-label>
          <q-item-section class="col row">
            <q-input outlined dense v-model="searchForm.roleName" />
          </q-item-section>
        </q-item>
        <q-item class="col-md-3 col-sm-6 col-xs-12 items-center">
          <q-item-section>
            <div class="row justify-center">
              <q-btn unelevated no-wrap label="查询" color="primary" class="q-mx-xs" icon="search" :loading="loading" @click="query()">
                <template v-slot:loading>
                  <q-spinner-ios class="on-center" />
                </template>
              </q-btn>
              <q-btn outline no-wrap unelevated label="重置" class="q-mx-xs" color="primary" icon="refresh" @click="searchReset" />
            </div>
          </q-item-section>
        </q-item>
      </div>
      <q-table flat row-key="id" color="primary" class="cross_table" separator="cell" :columns="columns" :data="list" :pagination.sync="pagination" :visible-columns="group" :rows-per-page-options="[10, 20, 50, 100]" :selection="mobile ? 'none' : 'multiple'" :selected.sync="selected" @request="query">
        <template v-slot:top="table">
          <div class="row no-wrap full-width">
            <q-space />
            <table-top-btns label="角色管理" modelName="role" :showAdd="true" :table="table" :selected="selected" :importing="importing" :exporting="exporting" :importExcelUrlFull="importExcelUrlFull" :columns="columns" @groupChange="groupChange" @add="add" @importExcel="importExcel" @exportExcel="exportExcel"
              @showConfirm="showConfirm" :showImport="false" :showExport="false" />
          </div>
        </template>
        <template #body-cell-opt="props">
          <q-td :props="props" :auto-width="true">
            <cc-btn label="授权" color="primary" icon="lock" @click="lock(props.row)"> <q-tooltip>授权</q-tooltip></cc-btn>
            <cc-btn label="关联" color="primary" icon="link" @click="link(props.row)"> <q-tooltip>关联</q-tooltip></cc-btn>
            <cc-btn label="复制" color="primary" icon="edit" @click="edit(props.row)"> <q-tooltip>编辑</q-tooltip></cc-btn>
            <btn-del label="角色" @confirm="del(props.row)" />
          </q-td>
        </template>
      </q-table>
    </div>
    <cc-dialog ref="dialog" :title="`${editType}角色`" @submit="submit">
      <div class="col-12">
        <h5><q-icon name="star" color="red" />角色名称：</h5>
        <q-input outlined dense v-model="form.roleName" type="text" clearable :rules="[requiredTest]" />
      </div>
      <div class="col-12">
        <h5><q-icon name="star" color="red" />角色编码：</h5>
        <q-input outlined dense v-model="form.roleCode" type="text" clearable :rules="[requiredTest]" />
      </div>
      <div class="col-12">
        <h5>描述：</h5>
        <q-input outlined dense v-model="form.description" type="text" clearable />
      </div>
    </cc-dialog>
    <cc-dialog ref="lockDialog" :loading="loading" title="角色权限配置" @submit="lockSubmit">
      <q-tree class="col-12" ref="treelist" :nodes="QueryTreeList" node-key="key" label-key="slotTitle" tick-strategy="leaf" :ticked.sync="ticked">
        <template #default-header="prop">
          <div class="row items-center">
            <div class>{{ prop.node.slotTitle }}</div>
          </div>
        </template>
      </q-tree>
    </cc-dialog>

    <cc-dialog ref="lockReportDialog" :loading="loading" title="角色报表权限配置" @submit="lockReportSubmit">
      <q-tree class="col-12" ref="treelist" :nodes="QueryTreeList" node-key="key" label-key="title" tick-strategy="strict" :ticked.sync="ticked">
        <template #default-header="prop">
          <div class="row items-center">
            <div class>{{ prop.node.title }}</div>
          </div>
        </template>
      </q-tree>
    </cc-dialog>

    <cc-dialog ref="linkDialog" :title="`[${selectedRole.roleName}] -- 关联用户`" :hasSubmit="false">
      <slave :id="selectedRole.id" />
    </cc-dialog>
    <confirm ref="confirmDialog" :msg="confirmMsg" @confirm="deleteBatch()" />
    <cc-loading :loading="loading" />
  </q-page>
</template>

<script>
import confirm from 'components/confirm';
import { IndexMixin } from 'boot/mixins';
import { requiredTest } from 'boot/inputTest';
import slave from './slave';

export default {
  name: 'SysRole',
  mixins: [IndexMixin],
  components: {
    confirm,
    slave,
  },
  data() {
    return {
      splitterModel: 50,
      QueryTreeList: [],
      ticked: [],
      initializeIds: [],
      selectedRole: {},
      roleId: '',
      columns: [
        {
          name: 'index',
          align: 'center',
          label: '序号',
          field: 'index',
          headerClasses: 'cc-table-index',
        },
        {
          name: 'roleName', align: 'center', label: '角色名称', field: 'roleName',
        },
        {
          name: 'roleCode', align: 'center', label: '角色编码', field: 'roleCode',
        },
        {
          name: 'description', align: 'center', label: '描述', field: 'description',
        },
        {
          name: 'opt', align: 'center', label: '操作', field: 'opt',
        },
      ],
      url: {
        list: '/sys/role/list',
        add: '/sys/role/add',
        edit: '/sys/role/edit',
        delete: '/sys/role/delete',
        deleteBatch: '/sys/role/deleteBatch',
        exportXlsUrl: '/sys/role/exportXls',
        importExcelUrl: '/sys/role/importExcel',
      },
    };
  },

  methods: {
    requiredTest,
    submit() {
      this.$axios.get(`/sys/role/checkRoleCode?roleCode=${this.form.roleCode}&id=${this.form.id}`).then((r) => {
        if (!r.success) {
          this.form.roleCode = '';
          this.$error('角色编码不能重复!');
        } else {
          let q;
          if (this.editType === '新建') {
            q = this.$axios.post(this.url.add, this.form);
          } else {
            q = this.$axios.put(this.url.edit, this.form);
          }
          return q.then((rs) => {
            this.$info(rs.message);
            this.$refs.dialog.hide();
          }).finally(() => {
            this.query();
          });
        }
      });
    },
    lockReport(prop) {
      this.roleId = prop.id;
      this.$axios.get('/sys/role/queryReportTreeList').then((res) => {
        if (res.success) {
          this.QueryTreeList = res.result.treeList;
          this.initializeIds = res.result.ids;
          this.$nextTick(() => {
            this.$refs.treelist.expandAll();
            this.queryRoleReport();
          });
        }
      });
      this.$refs.lockReportDialog.show();
    },
    lock(prop) {
      this.roleId = prop.id;
      this.$axios.get('/sys/role/queryTreeList').then((res) => {
        if (res.success) {
          this.QueryTreeList = res.result.treeList;
          this.initializeIds = res.result.ids;
          this.$nextTick(() => {
            this.$refs.treelist.expandAll();
            this.queryRolePermission();
          });
        }
      });

      this.$refs.lockDialog.show();
    },
    queryRoleReport() {
      this.$axios.get('/sms/reportNeaten/queryRoleReport', {
        params: {
          roleId: this.roleId,
        },
      }).then((resu) => {
        if (resu) {
          this.ticked = resu.result;
          this.initializeIds = resu.result;
        }
      });
    },
    queryRolePermission() {
      this.$axios.get('/sys/permission/queryRolePermission', {
        params: {
          roleId: this.roleId,
        },
      }).then((resu) => {
        if (resu) {
          this.ticked = resu.result;
          this.initializeIds = resu.result;
        }
      });
    },
    lockReportSubmit() {
      this.loading = true;
      this.$axios.post('/sms/reportNeaten/saveRoleReport', {
        lastpermissionIds: this.initializeIds.join(),
        permissionIds: this.ticked.join(),
        roleId: this.roleId,
      }).then((res) => {
        this.$info(res.message);
        if (res) {
          this.$refs.lockReportDialog.hide();
          this.query();
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    lockSubmit() {
      this.loading = true;
      this.$axios.post('/sys/permission/saveRolePermission', {
        lastpermissionIds: this.initializeIds.join(),
        permissionIds: this.ticked.join(),
        roleId: this.roleId,
      }).then((res) => {
        this.$info(res.message);
        if (res) {
          this.$refs.lockDialog.hide();
          this.query();
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    link(row) {
      this.selectedRole = row;
      this.$refs.linkDialog.show();
    },
    getChildren(key, sonList) {
      // 获取所有子节点，然后统一设定选定状态
      const node = this.$refs.treelist.getNodeByKey(key);
      const { children } = node;
      if (children && children.length > 0) {
        children.forEach((child) => {
          sonList.push(child.key);
          this.getChildren(child.key, sonList);
        });
      }
    },
  },
  watch: {
    ticked: {
      handler(n, o) {
        if (n.length === o.length) {
          return;
        }
        const sonList = [];
        if (n.length > o.length) {
          const node = n.find((c) => o.indexOf(c) === -1);
          // 当前被选定节点
          this.getChildren(node, sonList);
          const needAddList = sonList.filter((s) => n.indexOf(s) === -1);
          this.ticked.push(...needAddList);
        } else {
          // 当前被取消节点
          const node = o.find((c) => n.indexOf(c) === -1);
          this.getChildren(node, sonList);
          this.ticked = n.filter((s) => sonList.indexOf(s) === -1);
        }
      },

    },
  },

};
</script>

<style lang="stylus"></style>
